package server.config;

import server.HttpServlet;

import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 记录Host信息
 */
public class Host {
    /**
     * 虚拟主机名
     */
    private String name;

    /**
     * 虚拟主机目录
     */
    private String appBase;

    /**
     * Context配置映射
     */
    private Map<String, Context> contextMap = new ConcurrentHashMap<>();

    /**
     * 添加Context
     *
     * @param url Context对应的URL
     * @param context 要添加的Context
     */
    public void addContext(String url, Context context) {
        contextMap.put(url, context);
    }

    /**
     * 根据给定的URL，获取对应的Context
     *
     * @param url 给定的URL
     * @return 对应的Context
     */
    private Context getContext(String url) {
        int begin = url.indexOf('/');
        if (begin == -1) {
            return null;
        }

        int end = url.indexOf('/', begin + 1);
        if (end == -1) {
            return null;
        }

        String path = url.substring(begin + 1, end);
        return contextMap.get(path);
    }

    /**
     * 根据给定的URL，获取对应的Servlet
     *
     * @param url 给定的URL
     * @return 对应的Servlet
     */
    public HttpServlet resolveServlet(String url) {
        Context context = getContext(url);
        if (context == null) {
            return null;
        }

        String prefix = String.format("/%s", context.getPath());
        return context.resolveServlet(url.substring(prefix.length()));
    }

    /**
     * 根据给定的URL，获取对应的静态资源
     *
     * @param url 给定的URL
     * @return 对应的静态资源
     */
    public InputStream resolveStatic(String url) {
        Context context = getContext(url);
        if (context == null) {
            return null;
        }

        String prefix = String.format("/%s/", context.getPath());
        return context.resolveStatic(url.substring(prefix.length()), appBase);
    }

    public Map<String, Context> getContextMap() {
        return contextMap;
    }

    public void setContextMap(Map<String, Context> contextMap) {
        this.contextMap = contextMap;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAppBase() {
        return appBase;
    }

    public void setAppBase(String appBase) {
        this.appBase = appBase;
    }
}
